<?php
/**
 * Created by PhpStorm.
 * User: liuchaozhong
 * Date: 2018/7/30
 * Time: 下午4:34
 */
namespace App\Models;


use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;

class Category extends  Model
{
    use ModelTree,AdminBuilder;

    protected $table = 'category';
    public $is_hide_arr = ['显示', '隐藏'];

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);

        //修改模型tree字段对应数据表
        $this->setParentColumn('pid');
        $this->setOrderColumn('sort');
        $this->setTitleColumn('name');
    }

    public function byTree()
    {   
        $cate_all = $this->toTree();
        return $this->treeHandle($cate_all);
    }

    protected function treeHandle($data)
    {     
        //只循环三层
        $result = [];
        foreach ($data as $k => $v) {
            $result[$v['id']] = $v['name'];
            if(isset($v['children']) && is_array($v['children'])){
                $children1 = $v['children']; 
                foreach ($children1 as $k1 => $v1) {
                    $result[$v1['id']] = '_'.$v1['name'];
                    if(isset($v1['children']) && is_array($v1['children'])){
                        $children2 = $v1['children']; 
                        foreach ($children2 as $k2 => $v2) {
                            $result[$v2['id']] = '_ _'.$v2['name'];
                        }
                    }
                 }
            }
        }

        return $result;
    }

}